package cn.bughub.controller;

import cn.bughub.ColumnInfo;
import cn.bughub.init.VelocityInitializer;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
public class TestController {
    
    @GetMapping("/test")
    public String test() {
        List<ColumnInfo> columns = new ArrayList<>();
        columns.add(new ColumnInfo("id", "String", "主键"));
        columns.add(new ColumnInfo("name", "String", " 姓名"));
        columns.add(new ColumnInfo("age", "Integer", "年龄 "));
        columns.add(new ColumnInfo("address", "String", ""));
        
        VelocityInitializer.initVelocity();
        
        // 设置模板内容
        VelocityContext context = new VelocityContext();
        context.put("columns", columns);
        
        // 渲染模板
        StringWriter content = new StringWriter();
        Template tpl = Velocity.getTemplate("templates/Entity.java.vm", StandardCharsets.UTF_8.name());
        tpl.merge(context, content);
        
        // 指定文件路径
        String filePath = "D:\\test.java";
        
        // 使用 BufferedWriter 和 FileWriter 写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(String.valueOf(content));
            writer.newLine(); // 可选：写入换行符
            writer.write("This is another line.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        System.out.println("内容已成功写入文件: " + filePath);
        return content.toString();
    }
}
